<script setup>
import { onMounted, ref } from 'vue';
const props = defineProps({
    menu: {
        type: Object,
        required: true
    },
    containerClass: {
        type: String,
        default: "context-menu-container"
    },
    data: {
        type: Object
    }
})
const emits = defineEmits(["select", "on-show", "on-close"])
const x = ref(0)
const y = ref(0)
const visible = ref(0)

function showMenu(e) {
    x.value = e.clientX
    y.value = e.clientY
    visible.value = true
    emits("on-show", e.currentTarget)
}

function closeMenu() {
    visible.value = false
    emits("on-close")
}

onMounted(() => {
    window.addEventListener("click", closeMenu)
})

</script>

<template>
    <div :class="props.containerClass" @contextmenu.prevent.stop="showMenu">
        <slot></slot>
        <Teleport to="body">
            <div class="context-menu" :style="`--x: ${x}px; --y: ${y}px;`" v-if="visible">
                <p v-for="(item, i) in props.menu" :key="i"
                    @click="$emit('select', { label: item.label, data: props.data })">
                    {{ item.label }}
                </p>
            </div>
        </Teleport>
    </div>
</template>

<style scoped>
.context-menu {
    border-radius: 5px;
    background-color: #efefef;
    min-width: 130px;
    padding: 10px;
    position: fixed;
    left: var(--x);
    top: var(--y);

    p {
        padding: 0 5px 0 5px;
        margin: 0;
        cursor: pointer;
    }

    p:hover {
        padding: 0 5px 0 5px;
        border-radius: 5px;
        background-color: #5e8ef7;
        color: #efefef;
    }
}
</style>